<template>
<div class="map-page">
  <div class="loader-base" v-if="showLoad"><div class="loader-wrap"></div></div>
  <div class="map-top ft14">
    <div class="detail displayflex">
      <p class="flex1 gray">订单编号：{{bbilllist.BBillNo}}</p>
      <a @click="goDetail">查看详情</a>
      <i class="iconfont icon-right"></i>
    </div>
    <p class="lineTxt">提货地址：{{mainlist.DepartureProvince | province}}{{mainlist.DepartureCity | city}}{{mainlist.DepartureDistrict | district}}{{mainlist.DepartureAddress}}</p>
    <p class="lineTxt" v-if="mainlist.StartBusTerminal">中转地址：{{mainlist.StartBusTerminal.replace(/\//g, "")}}</p>
    <p class="lineTxt">收货地址：{{mainlist.ArrivalProvince | province}}{{mainlist.ArrivalCity | city}}{{mainlist.ArrivalDistrict | district}}{{mainlist.ArrivalAddress}}</p>
  </div>
  <div class="map-box" id="container">
  </div>
  <!-- <button class="btn btn-default" @click="getCurrent">定位当前位置</button>
  <button class="btn btn-default" @click="driving_route">规划路线</button>
  <div id="result"></div> -->
  
  <div class="map-bottom displayflex" v-if="userinfo.UserBizType == 'Cargowner'">
    <dl class="flex1">
      <dt class="ft14">当前配送员</dt>
      <dd class="ft17">{{DriverName}}  {{DriverTel}}</dd>
    </dl>
    <a class="icon" :href='"tel:"+DriverTel'><i class="iconfont icon-phone"></i></a>
  </div>
  <div class="map-bottom displayflex" v-if="userinfo.UserBizType == 'Driver'">
    <dl class="flex1">
      <dt class="ft14">收货人</dt>
      <dd class="ft17">{{mainlist.SendContacts}}  {{mainlist.SendContactsTel}}</dd>
    </dl>
    <a class="icon" :href="'tel:' + mainlist.SendContactsTel"><i class="iconfont icon-phone"></i></a>
    <!--<a class="icon" style="margin-left:10px; background-color:#3CB371" @click="wxNavigate"><i class="iconfont icon-navigation"></i></a>-->
  </div>
</div>
</template>

<script>
import imgstart from "@/assets/icon/start.png";
import imgend from "@/assets/icon/end.png";
import imgmid from "@/assets/icon/midway.png";
import {
  iosProvinces,
  iosCitys,
  iosCountys
} from "@/components/share/area/areaData_v2.js";
export default {
  data() {
    return {
      showLoad: false,
      bbilllist: [],
      mainlist: [],
      // goodslist: [],
      // HandOver: [],
      // DriverInfo: [],
      startlng: "",
      startlat: "",
      endlng: "",
      endlat: "",
      zzlng: "",
      zzlat: "",
      DriverTel:'',
      DriverName:'',
      wxLocation:{
        name: '', //目的地名称
        address: '', //目的地地址
        infoUrl: '', //底部链接，暂时不知道用来干啥
        latitude : '', // 纬度，浮点数，范围为90 ~ -90
        longitude : '', // 经度，浮点数，范围为180 ~ -180。
        speed : '', // 速度，以米/每秒计
        accuracy : '', // 位置精度
      },
    };
  },
  computed: {
    userinfo() {
      if (localStorage.UserInfo) {
        return JSON.parse(localStorage.UserInfo);
      }
    }
  },
  created() {
    this.getData();
    if (this.userinfo.UserBizType == "Cargowner") {
      // this.getExtra();
    }
  },
  mounted() {
    this.$nextTick(function() {
      // this.getMap();
      // this.transformValue('1');
    });
  },
  methods: {
    getData() {
      this.showLoad = true;
      var _this = this;
      var query = {
        Guid: this.$route.query.id
      };
      this.Ajax.post("GetOrderDetail", query).then(function(resp) {
        _this.showLoad = false;
        if (resp.IsSuccess) {
          _this.bbilllist = resp.Data.Bill;
          _this.mainlist = resp.Data.Main;
          // _this.goodslist = resp.Data.BbDetial;
          // _this.HandOver = resp.Data.HandOver;
          var startaddress =
            _this.province(_this.mainlist.DepartureProvince) +
            _this.city(_this.mainlist.DepartureCity) +
            _this.district(_this.mainlist.DepartureDistrict) +
            _this.mainlist.DepartureAddress;
          var endaddress =
            _this.province(_this.mainlist.ArrivalProvince) +
            _this.city(_this.mainlist.ArrivalCity) +
            _this.district(_this.mainlist.ArrivalDistrict) +
            _this.mainlist.ArrivalAddress;
          
          _this.transformValue("end",endaddress);
          _this.transformValue("start",startaddress);

          if(_this.mainlist.StartBusTerminal) {
            var zzaddress = _this.mainlist.StartBusTerminal.replace(/\//g, "");
            _this.transformValue("zz",zzaddress);
          }
          
          console.log(resp.Data.Tratvehicle);
          if (resp.Data.Tratvehicle) {
            _this.DriverTel =resp.Data.Tratvehicle.Driver1Tel;
            _this.DriverName=resp.Data.Tratvehicle.Driver1Name;
          }
        }
      });
    },
    getCoordinate(map) {
      var self = this;
      this.showLoad = true;
      var query = {
        MainPoGuid: this.mainlist.Guid,
      };
      this.Ajax.post("GetLastGPSCoordinate", query).then(function(resp) {
        self.showLoad = false;
        if(resp.IsSuccess && resp.Data.DrivePositionGIS)
        {
          var coord = JSON.parse(resp.Data.DrivePositionGIS);
          var posi = [];
          posi.push(coord.lng);
          posi.push(coord.lat);

          var marker = new AMap.Marker({
            position: posi,
            title: '当前车辆位置',
          });
          marker.setMap(map);
        } else {
          console.log('该订单未绑定GPS跟踪设备，当前仅可查看线路规划');
          // self.$vux.toast.show({
          //   type: "warn", //success, warn, cancel, text
          //   text: "该订单未绑定GPS跟踪设备，当前仅可查看线路规划",
          //   time: 3000,
          // });
        }
      });
    },
    goDetail() {
      this.$router.push({
        path: "/orderDetail",
        query: { id: this.$route.query.id }
      });
    },
    getMap() {
      var map = new AMap.Map("container", {
        resizeEnable: true,
        zoom: 10,
        center: [116.480983, 40.0958] //经纬度值
      });
      // this.getCurrent(map);
    },
    //定位当前位置
    getCurrent(map) {
      var geolocation = null;
      map.plugin("AMap.Geolocation", function() {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 10000, //超过10秒后停止定位，默认：无穷大
          maximumAge: 0, //定位结果缓存0毫秒，默认：0
          convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: "LB", //定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete); //返回定位信息
        AMap.event.addListener(geolocation, "error", onError); //返回定位出错信息
      });
      /*
       *解析定位结果
       */
      function onComplete(data) {
        var str = "定位成功:";
        str += "经度：" + data.position.getLng();
        str += "纬度：" + data.position.getLat();
        str += "精度：" + data.accuracy + " 米";
        str += "是否经过偏移：" + (data.isConverted ? "是" : "否");
        console.log(str);
      }
      /*
       *解析定位错误信息
       */
      function onError(data) {
        var str = "定位失败";
        str += "错误信息：";
        switch (data.info) {
          case "PERMISSION_DENIED":
            str += "浏览器阻止了定位操作";
            break;
          case "POSITION_UNAVAILBLE":
            str += "无法获得当前位置";
            break;
          case "TIMEOUT":
            str += "定位超时";
            break;
          default:
            str += "未知错误";
            break;
        }
        console.log(str);
      }
    },
    //规划路线
    driving_route() {
      var self =this;
      var map = new AMap.Map("container");
      //起、终点
      var value1_1 = this.startlng,
          value1_2 = this.startlat,
          value2_1 = this.endlng,
          value2_2 = this.endlat;
      var start_xy = new AMap.LngLat(value1_1, value1_2);
      var end_xy = new AMap.LngLat(value2_1, value2_2);
      
      //中转的玩意-------
      if(self.zzlat && self.zzlng){
        var zz_xy =[],
            path = {
              waypoints: []
            };
        zz_xy.push(self.zzlng);
        zz_xy.push(self.zzlat);
        path.waypoints.push(zz_xy);

        //打桩
        var marker = new AMap.Marker({
          map: map,
          position: zz_xy,
          icon: new AMap.Icon({  
              size: new AMap.Size(100, 100),  //图标大小  
              image: imgmid,  //图标地址  
              imageOffset: new AMap.Pixel(0, 37)  //偏移  
          })
        })
      }
      //中转的玩意-------

      //驾车导航
      var MDrive;
      map.plugin(["AMap.Driving"], function() {
        var DrivingOption = {
          //驾车策略，包括 LEAST_TIME，LEAST_FEE, LEAST_DISTANCE,REAL_TRAFFIC
          policy: AMap.DrivingPolicy.LEAST_TIME
        };
        MDrive = new AMap.Driving(DrivingOption); //构造驾车导航类
        AMap.event.addListener(MDrive, "complete", driving_routeCallBack); //返回导航查询结果
        if(!zz_xy) {
          MDrive.search(start_xy, end_xy); //根据起终点坐标规划驾车路线
        } else {
          MDrive.search(start_xy, end_xy, path); //根据起终点坐标规划驾车路线
        }
      });
      //导航结果展示
      var route_text,
          steps,
          roaddistance = 0,
          roadtime = 0;
      function driving_routeCallBack(data) {
        var routeS = data.routes;
        if (routeS.length <= 0) {
          console.log(
            "未查找到任何结果!建议：1.请确保所有字词拼写正确。未查找到任何结果!建议：1.请确保所有字词拼写正确。2.尝试不同的关键字。3.尝试更宽泛的关键字。"
          );
        } else {
          route_text = "";
          for (var v = 0; v < routeS.length; v++) {
            //驾车步骤数
            roaddistance += routeS[v].distance;
            roadtime += routeS[v].time;
            steps = routeS[v].steps;
            var route_count = steps.length;
            //行车距离（米）
            var distance = routeS[v].distance;
          }

          roadtime = timeFormat(roadtime);
          //输出行车路线指示
          route_text =
            "路线驾车时长" +
            roadtime +
            ",距离：" +
            roaddistance / 1000 +
            "公里" +
            route_text;
          console.log(route_text);
          drivingDrawLine();
          self.getCoordinate(map);
        }
      }
      //时间格式整理
      function timeFormat(time) {
        var minute = time / 60;
        var txt = "";
        if (minute > 60) {
          txt = Math.floor(minute / 60) + "小时";
          if (minute % 60 > 0) {
            txt += Math.ceil(minute % 60) + "分钟";
          }
        } else {
          txt = Math.ceil(minute) + "分钟";
        }
        return txt;
      }
      //绘制驾车导航路线
      function drivingDrawLine(s) {
        //起点、终点图标
        var sicon = new AMap.Icon({
          image: imgstart,
          size: new AMap.Size(100, 100),
          imageOffset: new AMap.Pixel(0, 37)
        });
        var startmarker = new AMap.Marker({
          icon: sicon, //复杂图标
          visible: true,
          position: start_xy,
          map: map,
          offset: {
            x: -16,
            y: -40
          }
        });
        var eicon = new AMap.Icon({
          image: imgend,
          size: new AMap.Size(100, 100),
          imageOffset: new AMap.Pixel(0, 37)
        });
        var endmarker = new AMap.Marker({
          icon: eicon, //复杂图标
          visible: true,
          position: end_xy,
          map: map,
          offset: {
            x: -16,
            y: -40
          }
        });

        //起点到路线的起点 路线的终点到终点 绘制无道路部分
        var extra_path1 = new Array();
        extra_path1.push(start_xy);
        extra_path1.push(steps[0].path[0]);
        var extra_line1 = new AMap.Polyline({
          map: map,
          path: extra_path1,
          strokeColor: "#9400D3",
          strokeOpacity: 0.7,
          strokeWeight: 4,
          strokeStyle: "dashed",
          strokeDasharray: [10, 5]
        });

        var extra_path2 = new Array();
        var path_xy = steps[steps.length - 1].path;
        extra_path2.push(end_xy);
        extra_path2.push(path_xy[path_xy.length - 1]);
        var extra_line2 = new AMap.Polyline({
          map: map,
          path: extra_path2,
          strokeColor: "#9400D3",
          strokeOpacity: 0.7,
          strokeWeight: 4,
          strokeStyle: "dashed",
          strokeDasharray: [10, 5]
        });

        var drawpath = new Array();
        for (var s = 0; s < steps.length; s++) {
          var plength = steps[s].path.length;
          for (var p = 0; p < plength; p++) {
            drawpath.push(steps[s].path[p]);
          }
        }
        var polyline = new AMap.Polyline({
          map: map,
          path: drawpath,
          strokeColor: "#9400D3",
          strokeOpacity: 0.7,
          strokeWeight: 4,
          strokeDasharray: [10, 5]
        });
        map.setFitView();
      }
    },
    transformValue(type,addr) {
      var self = this;
      var types = type;
      var geocoder = null;
      var map = new AMap.Map("container", {
        resizeEnable: true,
        zoom: 10,
        center: [116.480983, 40.0958] //经纬度值
      });
      map.plugin("AMap.Geocoder", function() {
        geocoder = new AMap.Geocoder({
          // city: "010" //城市，默认：“全国”
        });
        //地理编码
        geocoder.getLocation(addr, function(status, result) {
          if (status === "complete" && result.info === "OK") {
            //TODO:获得了有效经纬度，可以做一些展示工作
            //比如在获得的经纬度上打上一个Marker
            var lng = result.geocodes[0].location.lng,
                lat = result.geocodes[0].location.lat;
            if (types == "start") {
              self.startlng = lng;
              self.startlat = lat;
            } else if (types == "end") {
              self.endlng = lng;
              self.endlat = lat;
            } else if (types == "zz") {
              self.zzlng = lng;
              self.zzlat = lat;
            };
            if(self.startlng&&self.startlat&&self.endlng&&self.endlat){
              console.log(self.startlng,self.startlat,self.endlng,self.endlat)
              self.driving_route();
            }
          } else {
            console.log("获取经纬度失败失败");
            //获取经纬度失败
          }
        });
      });
    },
    province(val) {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(val)) {
        return val;
      }
      if (val && val != null && val != "undefined") {
        for (var i = 0; i < iosProvinces.length; i++) {
          if (iosProvinces[i].id == val) {
            return iosProvinces[i].value;
          }
        }
      }
    },
    city(val) {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(val)) {
        return val;
      }
      if (val && val != null && val != "undefined") {
        for (var i = 0; i < iosCitys.length; i++) {
          if (iosCitys[i].id == val) {
            return iosCitys[i].value;
          }
        }
      }
    },
    district(val) {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(val)) {
        return val;
      }
      if (val && val != null && val != "undefined") {
        for (var i = 0; i < iosCountys.length; i++) {
          if (iosCountys[i].id == val) {
            return iosCountys[i].value;
          }
        }
      }
    },

    // wxNavigate(){
    //   var self = this;
    //   this.wxLocation.latitude = this.endlat;
    //   this.wxLocation.longitude = this.endlng;
    //   this.wxLocation.name = this.mainlist.ArrivalAddress;
    //   this.wxLocation.address = this.province(this.mainlist.ArrivalProvince) + this.city(this.mainlist.ArrivalCity) + this.district(this.mainlist.ArrivalDistrict) + this.mainlist.ArrivalAddress;
    //   this.wxLocation.infoUrl = this.bbilllist.Guid;

    //   this.jWeixin.openLocation({
    //     latitude: self.wxLocation.latitude, // 纬度，浮点数，范围为90 ~ -90
    //     longitude: self.wxLocation.longitude, // 经度，浮点数，范围为180 ~ -180。
    //     name: self.wxLocation.name, // 位置名
    //     address: self.wxLocation.address, // 地址详情说明
    //     scale: 1, // 地图缩放级别,整形值,范围从1~28。默认为最大
    //     infoUrl: self.wxLocation.infoUrl // 在查看位置界面底部显示的超链接,可点击跳转
    //   });
    // },
  }
};
</script>
